
package com.pikts.acc2blender;

import com.pikts.acc2blender.data.DataStruct;
import com.pikts.acc2blender.data.Fifo;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
public class SensorListener implements SensorEventListener {
  /**
   *  Called when the activity is first created. 
   *  Context context;
   */
  private static final String TAG =  "Acc2BlenderLog";

  private SensorManager sensorManager;

  private SensorEventListener sensorEventListener;

  private int SENSOR_DELAY =  SensorManager.SENSOR_DELAY_FASTEST;

  private com.pikts.acc2blender.data.Fifo fifoAcc;

  private com.pikts.acc2blender.data.Fifo fifoRot;

  /**
   * DELETE ME
   */
  int i = 0;

  @Override
  public void onSensorChanged(SensorEvent sensorEvent) {
		synchronized (this) {
			try {
				if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
					fifoAcc.push(new DataStruct(sensorEvent.timestamp,
							sensorEvent.values[0], sensorEvent.values[1],
							sensorEvent.values[2]));
	//				Log.v(TAG, "pushed sensors value");
					i++;
				}
				if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
					fifoRot.push(new DataStruct(sensorEvent.timestamp,
							sensorEvent.values[0], sensorEvent.values[1],
							sensorEvent.values[2]));
				}
				if (i>99) {
					Log.d(TAG, "sensor changed 100 times");
					i=0;
				}
			} catch (Exception e) {
				Log.e(TAG, "error in sensorListener: ", e);
			}
		}
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
  }

  public void restartAccelerometer() {
		sensorManager.unregisterListener(sensorEventListener);
		sensorManager.registerListener(sensorEventListener,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SENSOR_DELAY);
		sensorManager.registerListener(sensorEventListener,
				sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SENSOR_DELAY);

  }

  public SensorListener(com.pikts.acc2blender.data.Fifo fifoAcc, com.pikts.acc2blender.data.Fifo fifoRot, Context context) {
		sensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		this.fifoAcc = fifoAcc;
	//	this.fifoAcc = new Fifo();
		this.fifoRot = fifoRot;
	//	this.fifoRot = new Fifo();
  }

  public void destroy() {
		// Unregister the listener
		sensorManager.unregisterListener(sensorEventListener);
  }

  public void resume() {
		sensorEventListener = this;
		// Register this class as a listener for the accelerometer sensor
		sensorManager.registerListener(sensorEventListener,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SENSOR_DELAY);
		// ...and the orientation sensor
		sensorManager.registerListener(sensorEventListener,
				sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SENSOR_DELAY);
  }

}
